<template>
  <view>
    <!-- 遮罩层 -->
    <view class="mask" :class="{ 'mask-show': visible }" @click="close"></view>

    <!-- 侧边栏菜单 -->
    <view class="side-menu" :class="{ 'side-menu-show': visible }">
      <!-- 用户信息区域 -->
      <view class="user-info">
        <image class="avatar" src="/static/logo/logo.png"></image>
        <view class="username">{{ username }}</view>
      </view>

      <!-- 菜单项 -->
      <view class="menu-items">
        <view class="menu-item" @click="navigateTo('/pages/labels/labels')">
          <view class="menu-icon">
            <image class="icon" src="/static/svgs/tag.svg"></image>
          </view>
          <view class="menu-text">全部标签</view>
        </view>
        <view
          class="menu-item"
          @click="navigateTo('/pages/completed-todos/completed-todos')"
        >
          <view class="menu-icon">
            <image class="icon" src="/static/svgs/completed.svg"></image>
          </view>
          <view class="menu-text">已完成待办</view>
        </view>
        <view class="menu-item" @click="navigateTo('/pages/trash/trash')">
          <view class="menu-icon">
            <image class="icon" src="/static/svgs/delete.svg"></image>
          </view>
          <view class="menu-text">回收站</view>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="action-buttons">
        <button class="action-button delete-account" @click="deleteAccount">
          注销账号
        </button>
        <button class="action-button logout" @click="logout">退出登录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, ref } from "vue";
import userApi from "@/api/user";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["close"]);
const username = ref(uni.getStorageSync("zbox-username") || "ZBOX");

const close = () => {
  emit("close");
};

const navigateTo = (url) => {
  close();
  setTimeout(() => {
    if (url.includes("/pages/index/index")) {
      uni.reLaunch({
        url: url,
        fail: (err) => {
          console.error("导航失败:", err);
          uni.navigateTo({
            url: url,
          });
        },
      });
    } else {
      uni.navigateTo({
        url: url,
        fail: (err) => {
          console.error("导航失败:", err);
          uni.redirectTo({
            url: url,
          });
        },
      });
    }
  }, 200);
};

const clearUserData = () => {
  // 清除本地存储的用户数据
  uni.removeStorageSync("zbox-token");
  uni.removeStorageSync("zbox-userId");
  uni.removeStorageSync("zbox-username");
  uni.removeStorageSync("zbox-account");
};

const deleteAccount = () => {
  close();
  setTimeout(() => {
    uni.showModal({
      title: "注销账号",
      content: "确定要注销账号吗？此操作不可恢复。",
      confirmColor: "#FF3B30",
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({
              title: "处理中...",
            });

            const result = await userApi.writeOff();

            uni.hideLoading();

            if (result.success && result.code === "00000") {
              // 清除用户数据
              clearUserData();

              uni.showToast({
                title: result.data || "账号已注销",
                icon: "success",
              });

              // 注销后返回登录页
              setTimeout(() => {
                uni.reLaunch({
                  url: "/pages/login/login",
                });
              }, 1500);
            } else {
              uni.showToast({
                title: result.msg || "注销失败",
                icon: "error",
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error("注销账号失败:", error);
            uni.showToast({
              title: "注销失败，请稍后重试",
              icon: "error",
            });
          }
        }
      },
    });
  }, 200);
};

const logout = () => {
  close();
  setTimeout(() => {
    uni.showModal({
      title: "退出登录",
      content: "确定要退出登录吗？",
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({
              title: "退出中...",
            });

            const result = await userApi.logout();

            uni.hideLoading();

            if (result.success && result.code === "00000") {
              // 清除用户数据
              clearUserData();

              uni.showToast({
                title: result.data || "退出成功",
                icon: "success",
              });

              // 跳转到登录页
              setTimeout(() => {
                uni.reLaunch({
                  url: "/pages/login/login",
                  fail: (err) => {
                    console.error("跳转登录页失败:", err);
                    uni.redirectTo({
                      url: "/pages/login/login",
                    });
                  },
                });
              }, 1500);
            } else {
              uni.showToast({
                title: result.msg || "退出失败",
                icon: "error",
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error("退出登录失败:", error);
            uni.showToast({
              title: "退出失败，请稍后重试",
              icon: "error",
            });
          }
        }
      },
    });
  }, 200);
};

const showToast = (message) => {
  close();
  setTimeout(() => {
    uni.showToast({
      title: message,
      icon: "none",
    });
  }, 200);
};
</script>

<style scoped>
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s;
  z-index: 9998;
}

.mask-show {
  opacity: 1;
  visibility: visible;
}

.side-menu {
  position: fixed;
  top: 0;
  left: -70%;
  width: 70%;
  height: 100%;
  background-color: #fff;
  z-index: 9999;
  transition: all 0.3s ease-out;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.side-menu-show {
  left: 0;
}

.user-info {
  padding: 60rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #4361ee;
  color: #fff;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
}

.menu-items {
  flex: 1;
  padding: 30rpx 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
}

.menu-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  width: 40rpx;
  height: 40rpx;
  color: #4361ee;
}

.menu-text {
  font-size: 30rpx;
  color: #333;
}

/* 底部操作按钮样式 */
.action-buttons {
  padding: 30rpx 40rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-button {
  height: 80rpx;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin-bottom: 20rpx;
  border: none;
}

.action-button:last-child {
  margin-bottom: 0;
}

.delete-account {
  background-color: #ffffff;
  color: #ff3b30;
  border: 1px solid #ff3b30;
}

.logout {
  background-color: #4361ee;
  color: #ffffff;
}
</style>
